import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string; memberId: string } }
) {
  try {
    // 验证项目是否存在
    const project = await db.researchProject.findUnique({
      where: { id: (await params).id }
    })
    
    if (!project) {
      return NextResponse.json(
        { error: 'Research project not found' },
        { status: 404 }
      )
    }

    // 获取团队成员
    const teamMembers = project.teamMembers ? JSON.parse(project.teamMembers) : []
    const member = teamMembers.find((m: any) => m.id === params.memberId)
    
    if (!member) {
      return NextResponse.json(
        { error: 'Team member not found' },
        { status: 404 }
      )
    }

    return NextResponse.json(member)
  } catch (error) {
    console.error('Error fetching team member:', error)
    return NextResponse.json(
      { error: 'Failed to fetch team member' },
      { status: 500 }
    )
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string; memberId: string } }
) {
  try {
    const body = await request.json()
    
    // 验证项目是否存在
    const project = await db.researchProject.findUnique({
      where: { id: (await params).id }
    })
    
    if (!project) {
      return NextResponse.json(
        { error: 'Research project not found' },
        { status: 404 }
      )
    }

    const {
      name,
      email,
      phone,
      department,
      position,
      role,
      joinDate,
      leaveDate,
      status,
      responsibilities,
      skills,
      avatar,
      updatedBy
    } = body

    // 验证必填字段
    if (!name || !email || !role || !status || !updatedBy) {
      return NextResponse.json(
        { error: 'Missing required fields: name, email, role, status, updatedBy' },
        { status: 400 }
      )
    }

    // 获取现有团队成员
    const teamMembers = project.teamMembers ? JSON.parse(project.teamMembers) : []
    const memberIndex = teamMembers.findIndex((m: any) => m.id === params.memberId)
    
    if (memberIndex === -1) {
      return NextResponse.json(
        { error: 'Team member not found' },
        { status: 404 }
      )
    }

    // 更新成员信息
    const updatedMember = {
      ...teamMembers[memberIndex],
      name,
      email,
      phone: phone || '',
      department: department || '',
      position: position || '',
      role,
      joinDate: joinDate || teamMembers[memberIndex].joinDate,
      leaveDate: leaveDate || null,
      status,
      responsibilities: responsibilities || '',
      skills: skills || [],
      avatar: avatar || '',
      updatedBy,
      updatedAt: new Date().toISOString()
    }

    // 更新团队成员列表
    teamMembers[memberIndex] = updatedMember

    // 更新项目的团队成员信息
    const updatedProject = await db.researchProject.update({
      where: { id: (await params).id },
      data: {
        teamMembers: JSON.stringify(teamMembers),
        updateTime: new Date()
      },
      include: {
        creator: {
          select: {
            id: true,
            name: true,
            email: true
          }
        },
        updater: {
          select: {
            id: true,
            name: true,
            email: true
          }
        }
      }
    })

    // 创建历史记录
    await db.projectHistory.create({
      data: {
        projectId: (await params).id,
        action: 'TEAM_MEMBER_UPDATED',
        description: `更新团队成员: ${name} (${role})`,
        userId: updatedBy,
        fromLevel1: project.level1,
        fromLevel2: project.level2,
        toLevel1: project.level1,
        toLevel2: project.level2
      }
    })

    return NextResponse.json(updatedMember)
  } catch (error) {
    console.error('Error updating team member:', error)
    return NextResponse.json(
      { error: 'Failed to update team member' },
      { status: 500 }
    )
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string; memberId: string } }
) {
  try {
    // 获取请求体中的userId
    const body = await request.json()
    const { userId } = body
    
    if (!userId) {
      return NextResponse.json(
        { error: 'Missing required field: userId' },
        { status: 400 }
      )
    }
    
    // 验证项目是否存在
    const project = await db.researchProject.findUnique({
      where: { id: (await params).id }
    })
    
    if (!project) {
      return NextResponse.json(
        { error: 'Research project not found' },
        { status: 404 }
      )
    }

    // 获取现有团队成员
    const teamMembers = project.teamMembers ? JSON.parse(project.teamMembers) : []
    const memberIndex = teamMembers.findIndex((m: any) => m.id === params.memberId)
    
    if (memberIndex === -1) {
      return NextResponse.json(
        { error: 'Team member not found' },
        { status: 404 }
      )
    }

    const deletedMember = teamMembers[memberIndex]
    
    // 从团队成员列表中移除
    teamMembers.splice(memberIndex, 1)

    // 更新项目的团队成员信息
    const updatedProject = await db.researchProject.update({
      where: { id: (await params).id },
      data: {
        teamMembers: JSON.stringify(teamMembers),
        updateTime: new Date()
      },
      include: {
        creator: {
          select: {
            id: true,
            name: true,
            email: true
          }
        },
        updater: {
          select: {
            id: true,
            name: true,
            email: true
          }
        }
      }
    })

    // 创建历史记录
    await db.projectHistory.create({
      data: {
        projectId: (await params).id,
        action: 'TEAM_MEMBER_REMOVED',
        description: `移除团队成员: ${deletedMember.name} (${deletedMember.role})`,
        userId,
        fromLevel1: project.level1,
        fromLevel2: project.level2,
        toLevel1: project.level1,
        toLevel2: project.level2
      }
    })

    return NextResponse.json({ 
      message: 'Team member deleted successfully',
      memberId: params.memberId 
    })
  } catch (error) {
    console.error('Error deleting team member:', error)
    return NextResponse.json(
      { error: 'Failed to delete team member' },
      { status: 500 }
    )
  }
}